<?php
/* -------------------------------------------------------------------------------------
* 	ID:						$Id: specials.php 110 2013-09-21 12:07:42Z phone.mueller@googlemail.com $
* 	Letzter Stand:			$Revision: 110 $
* 	zuletzt geaendert von:	$Author: siekiera $
* 	Datum:					$Date: 2013-09-21 12:07:42 +0000 (Sat, 21 Sep 2013) $
*
* 	SEO:mercari by Siekiera Media
* 	http://www.seo-mercari.de
*
* 	Copyright (c) since 2011 SEO:mercari
* --------------------------------------------------------------------------------------
* 	based on:
* 	(c) 2000-2001 The Exchange Project  (earlier name of osCommerce)
* 	(c) 2002-2003 osCommerce - www.oscommerce.com
* 	(c) 2003     nextcommerce - www.nextcommerce.org
* 	(c) 2005     xt:Commerce - www.xt-commerce.com
*
* 	Released under the GNU General Public License
* ----------------------------------------------------------------------------------- */

require('includes/application_top.php');

require(DIR_FS_CATALOG.DIR_WS_CLASSES.'class.price.php');
$price = new price(DEFAULT_CURRENCY, $_SESSION['customers_status']['customers_status_id'], $db);

require_once(DIR_FS_INC.'inc.get_tax_rate.php');

switch ($_GET['action']) {
    case 'setflag':
		$db->db_query("UPDATE 
							".TABLE_SPECIALS." 
						SET 
							status = '".$_GET['flag']."', 
							date_status_change = NOW(), 
							specials_last_modified = NOW() 
						WHERE 
							specials_id = ".$db->db_prepare($_GET['id']));
		redirect(href_link(FILENAME_SPECIALS, 'page='.$_GET['page'], 'NONSSL'));
		break;

    case 'insert':
    	$expires_date = '';
		if ($_POST['date'] !='')
			$expires_date = substr($_POST['date'],6,4).'-'.substr($_POST['date'],3,2).'-'.substr($_POST['date'],0,2).' 00:00:00';
    	
    	$tax = $db->db_query("SELECT 
									tr.tax_rate 
								FROM 
									".TABLE_TAX_RATES." tr, 
									".TABLE_PRODUCTS." p  
								WHERE 
									tr.tax_class_id = p.products_tax_class_id 
								AND 
									p.products_id = '".$_POST['products_id']."'");
    	
    	$new_special_insert = $db->db_query("SELECT 
													products_id,
													products_tax_class_id, 
													products_price 
												FROM 
													".TABLE_PRODUCTS." 
												WHERE 
													products_id = '".(int)$_POST['products_id']."'");

    	$insert_arr = array('products_id' => $_POST['products_id'],
    						'specials_quantity' => $_POST['specials_quantity'],
    						'specials_date_added' => 'NOW()',
    						'expires_date' => $expires_date,
    						'status' => '1');
  
    	$groups = get_customers_statuses();
		foreach($groups AS $group) {
			$post_price = $_POST['products_specials_price_'.$group['id']];
			$post_price = str_replace(',', '.', $post_price);
			if(PRICE_IS_BRUTTO=='true' && substr($post_price, -1) != '%')
				$post_price = ($post_price/($tax->fields['tax_rate']+100)*100);
			if(substr($post_price, -1) == '%')
				$_POST['specials_price_'.$group['id']] = ($new_special_insert->fields['products_price'] - ((substr($post_price, 0, -1) / 100) * $_POST['products_price']));
			
			$insert_arr = array_merge($insert_arr, array('specials_price_'.$group['id'] => $post_price));
		}
		
		$db->db_perform(TABLE_SPECIALS, $insert_arr);
		redirect(href_link(FILENAME_SPECIALS, 'sID='.$db->db_insert_id().(isset($_GET['page']) ? '&page='.$_GET['page'] : '')));
		break;

    case 'update':
    	$expires_date = '';
		if ($_POST['date'] !='')
			$expires_date = substr($_POST['date'],6,4).'-'.substr($_POST['date'],3,2).'-'.substr($_POST['date'],0,2).' 00:00:00';
    	
    	$tax = $db->db_query("SELECT 
									tr.tax_rate 
								FROM 
									".TABLE_TAX_RATES." tr, 
									".TABLE_PRODUCTS." p  
								WHERE 
									tr.tax_class_id = p.products_tax_class_id 
								AND 
									p.products_id = '".$_POST['products_id']."'");
    	
    	$new_special_insert = $db->db_query("SELECT 
													products_id,
													products_tax_class_id, 
													products_price 
												FROM 
													".TABLE_PRODUCTS." 
												WHERE 
													products_id = '".(int)$_POST['products_id']."'");

    	$update_arr = array('specials_quantity' => $_POST['specials_quantity'],
    						'specials_last_modified' => 'NOW()',
    						'expires_date' => $expires_date);
  
    	$groups = get_customers_statuses();
		foreach($groups AS $group) {
			$post_price = $_POST['products_specials_price_'.$group['id']];
			$post_price = str_replace(',', '.', $post_price);
			if(PRICE_IS_BRUTTO=='true' && substr($post_price, -1) != '%')
				$post_price = ($post_price/($tax->fields['tax_rate']+100)*100);
			if(substr($post_price, -1) == '%')
				$post_price = ($new_special_insert->fields['products_price'] - ((substr($post_price, 0, -1) / 100) * $new_special_insert->fields['products_price']));
			
			$update_arr = array_merge($update_arr, array('specials_price_'.$group['id'] => $post_price));
		}
		
		$db->db_perform(TABLE_SPECIALS, $update_arr, 'update', "specials_id = '".$_POST['specials_id']."'");
		
		redirect(href_link(FILENAME_SPECIALS, 'sID='.$_POST['specials_id'].(isset($_GET['page']) ? '&page='.$_GET['page'] : '')));
		break;

	case 'deleteconfirm':
		$specials_id = $_GET['sID'];

		$db->db_query("DELETE FROM ".TABLE_SPECIALS." WHERE specials_id = '".$specials_id."'");

		redirect(href_link(FILENAME_SPECIALS, (isset($_GET['page']) ? 'page='.$_GET['page'] : '')));
		break;
		
	default: // Alle Kundengruppen anlegen, wenn welche fehlen
		$groups = get_customers_statuses();
		foreach($groups AS $group) {
			$check_col = $db->db_query("SHOW COLUMNS FROM ".TABLE_SPECIALS." LIKE 'specials_price_".$group['id']."'");
			if($check_col->_numOfRows < 1)
				$db->db_query("ALTER TABLE ".TABLE_SPECIALS." ADD specials_price_".$group['id']." DECIMAL(15,4) NOT NULL;");
		}
		break;
}

function getSpecialPriceField($sprice = '', $cg_id, $tax) {
	global $price;
	
	if(!empty($sprice) && $sprice !='0') {
		$sprice_brutto = round($sprice * ((100 + get_tax_rate($tax)) / 100), 2);
		
		if(PRICE_IS_BRUTTO == 'true') {
			return TEXT_BRUTTO.draw_input_field('products_specials_price_'.$cg_id, $sprice_brutto, 'size="10" style="text-align:right;color:#b20000"').$price->currencies[$price->actualCurr]['symbol_right'].'&nbsp;-&nbsp;'.TEXT_NETTO.'<b>'.$price->format($sprice, false).'</b> '.$price->currencies[$price->actualCurr]['symbol_right'];
		} else {
			return TEXT_NETTO.draw_input_field('products_specials_price_'.$cg_id, $price->format($sprice, false), 'size="10" style="text-align:right;color:#b20000"').$price->currencies[$price->actualCurr]['symbol_right'].'&nbsp;-&nbsp;'.TEXT_BRUTTO.'<b>'.$sprice_brutto.'</b> '.$price->currencies[$price->actualCurr]['symbol_right'];
		}
	} else
		return draw_input_field('products_specials_price_'.$cg_id, '', 'size="10"');
}

function DiscountByGroup($gid, $sid) {
	global $db, $price;

	$get = $db->db_query("SELECT
								p.products_tax_class_id,
								p.products_id,
								p.products_price,
								s.specials_price_".(int)$gid."
							FROM
								".TABLE_PRODUCTS." p,
								".TABLE_SPECIALS." s
							WHERE
								p.products_id = s.products_id
							AND
								s.specials_id = '".(int)$sid."'");

	return number_format(100-(($get->fields['specials_price_'.$gid] / $price->format($get->fields['products_price'], false, $get->fields['products_tax_class_id'])) * 100)).'%';
}

require(DIR_WS_INCLUDES.'metatag.php');
?>
</head>
<body>
<?php require(DIR_WS_INCLUDES.'header.php'); ?>
<div id="wrapper">
<table class="outerTable" cellpadding="0" cellspacing="0">
	<tr>
		<td class="columnLeft2" width="<?php echo BOX_WIDTH; ?>" valign="top">
			<?php require(DIR_WS_INCLUDES.'column_left.php'); ?>
		</td>
		<td class="boxCenter" valign="top">
			<table width="100%" cellpadding="2">
				<tr>
					<td width="100%">
						<table class="table_pageHeading" border="0" width="100%" cellspacing="0" cellpadding="0">
							<tr>
								<td class="pageHeading"><?php echo HEADING_TITLE; ?></td>
							</tr>
						</table>
					</td>
				</tr>
				<?php if(!isset($_GET['action'])) { ?>
				<tr>
					<td align="right">
						<a class="button" onclick="this.blur();" href="<?php echo href_link(FILENAME_SPECIALS, 'action=new'.(isset($_GET['page']) ? 'page='.$_GET['page'] : '')) ?>">
							<?php echo BUTTON_NEW_PRODUCTS ?>
						</a>
					</td>
				</tr>
				<?php
				}
				if(($_GET['action'] == 'new') || ($_GET['action'] == 'edit')){
				    $form_action = 'insert';
				    if(($_GET['action'] == 'edit') && ($_GET['sID'])) {
						$form_action = 'update';

						$product = $db->db_query("SELECT
													p.products_tax_class_id,
													p.products_id,
													pd.products_name,
													p.products_price,
													s.specials_quantity,
													s.expires_date,
													DATE_FORMAT(s.expires_date, '%d.%m.%Y') AS date
												FROM
													".TABLE_PRODUCTS." p,
													".TABLE_PRODUCTS_DESCRIPTION." pd,
													".TABLE_SPECIALS." s
												WHERE
													p.products_id = pd.products_id
												AND
													pd.language_id = '".(int)$_SESSION['languages_id']."'
												AND
													p.products_id = s.products_id
												AND
													s.specials_id = '".(int)$_GET['sID']."'");
				    } else {
						$sInfo = new objectInfo(array());
						$specials_array = array();
						$specials = $db->db_query("SELECT
														p.products_id
													FROM
														".TABLE_PRODUCTS." p,
														".TABLE_SPECIALS." s
													WHERE
														s.products_id = p.products_id");
						while (!$specials->EOF){
							$specials_array[] = $specials->fields['products_id'];
							$specials->MoveNext();
						}
				    }
				?>
      			<tr>
        			<td><br />
        				<?php
        					echo draw_form('special', FILENAME_SPECIALS, 'action='.$form_action.(isset($_GET['page']) ? 'page='.$_GET['page'] : ''));
        				?>
						<?php if ($form_action == 'update') echo draw_hidden_field('specials_id', $_GET['sID']); ?>
							<table cellpadding="6">
								<tr>
									<td class="main" width="120">
										<?php echo TEXT_SPECIALS_PRODUCT; echo ($product->fields['products_name']) ? "" :  ''; ?>
									</td>
										<?php
											if(PRICE_IS_BRUTTO == 'true'){
												$products_price_raw = $product->fields['products_price'];
												$products_price = $price->format($product->fields['products_price'], true, $product->fields['products_tax_class_id'], true);
											} else {
												$products_price_raw = $product->fields['products_price'];
												$products_price = $price->format($product->fields['products_price'], true, 0, true);
											}		
									   ?>
									<td class="main">
										<?php
											echo '<input type="hidden" name="products_id" value="'.$product->fields['products_id'].'" />';
											if($product->fields['products_name'] !='') {
												echo $product->fields['products_name'].' <small>('.$products_price. ')</small>';
											} else
												echo draw_products_pull_down('products_id', '', $specials_array);
										?>
									</td>
								</tr>
								<?php 
									$groups = get_customers_statuses();
									foreach($groups AS $group) {
										if($product->fields['products_name'] !='') {
											$sprice = $db->db_query("SELECT
																		specials_price_".$group['id']."
																	FROM
																		".TABLE_SPECIALS." s
																	WHERE
																		products_id = '".$product->fields['products_id']."' ");
										
											echo '	<tr>
														<td class="main">'.$group['text'].'</td>
														<td class="main"><nobr>'.getSpecialPriceField($sprice->fields['specials_price_'.$group['id']], $group['id'], $product->fields['products_tax_class_id']).'</nobr></td>
													</tr>';
										} else {
											echo '	<tr>
														<td class="main">'.$group['text'].'</td>
														<td class="main"><nobr>'.getSpecialPriceField('', $group['id'], '').'</nobr></td>
													</tr>';
										}
									}
								?>
								<tr>
									<td class="main"><?php echo TEXT_SPECIALS_SPECIAL_QUANTITY; ?>&nbsp;</td>
									<td class="main"><?php echo draw_input_field('specials_quantity', ($product->fields['specials_quantity'] !='0' ? $product->fields['specials_quantity'] : '')); ?></td>
								</tr>
								<tr>
									<td class="main"><?php echo TEXT_SPECIALS_EXPIRES_DATE; ?>&nbsp;</td>
									<td class="main">
										<input type="text" name="date" class="datepickers" value="<?php echo ($product->fields['date']!='00.00.0000' ? $product->fields['date'] : ''); ?>" />
										<script type="text/javascript">
											$(function(){
												$('.datepickers').datepicker({minDate: new Date(<?php echo date('Y').','.date('m').'-1,'.date('d'); ?>),
												dateFormat : 'dd.mm.yy'});
											});
										</script>
									</td>
								</tr>
							</table>
							<table border="0" width="100%" cellspacing="0" cellpadding="2">
								<tr>
									<td class="main"><br /><?php echo TEXT_SPECIALS_PRICE_TIP; ?></td>
									<td class="main" align="right" valign="top">
									<br />
										<button type="submit" class="button">
											<?php echo (($form_action == 'insert') ? BUTTON_INSERT : BUTTON_UPDATE) ?>
										</button> 
										<a class="button" onclick="this.blur();" href="<?php echo href_link(FILENAME_SPECIALS, (isset($_GET['sID']) ? 'sID='.$_GET['sID'] : '').(isset($_GET['page']) ? '&page='.$_GET['page'] : '')) ?>"><?php echo BUTTON_CANCEL ?></a>
									</td>
								</tr>
							</table>
						</form>
        			</td>
      			</tr>
      			<tr>
				<?php } else { 
					$groups = get_customers_statuses();
				?>
					<tr>
						<td>
							<table border="0" width="100%" cellspacing="0" cellpadding="0">
								<tr>
									<td valign="top">
										<table border="0" width="100%" cellspacing="0" cellpadding="2" class="dataTable">
											<tr class="dataTableHeadingRow">
												<td class="dataTableHeadingContent"><?php echo TABLE_HEADING_PRODUCTS; ?></td>
												<?php
													foreach($groups as $group) {
														echo '<td class="dataTableHeadingContent" align="center">'.$group['text'].'</td>';
													}
												?>
												<td class="dataTableHeadingContent" align="center"><?php echo TABLE_HEADING_STATUS; ?></td>
												<td class="dataTableHeadingContent" align="right"><?php echo TABLE_HEADING_ACTION; ?>&nbsp;</td>
											</tr>
											<?php
												$sql = "SELECT 
															p.products_id, 
															pd.products_name,
															p.products_tax_class_id,
															p.products_price,
															s.specials_id,
															s.specials_date_added, 
															s.specials_last_modified, 
															s.expires_date, 
															s.date_status_change, 
															s.status 
														FROM 
															".TABLE_PRODUCTS." p, 
															".TABLE_SPECIALS." s, 
															".TABLE_PRODUCTS_DESCRIPTION." pd 
														WHERE 
															p.products_id = pd.products_id 
														AND 
															pd.language_id = '".$_SESSION['languages_id']."' 
														AND 
															p.products_id = s.products_id 
														ORDER BY 
															pd.products_name";
												
												$query = page_break_create($_POST['per_site'], $_GET['page'], $sql, 'specials.php');
												$specials = $query['query'];
												while(!$specials->EOF) {
													if(((!$_GET['sID']) || ($_GET['sID'] == $specials->fields['specials_id'])) && (!$sInfo)) {
														$products = $db->db_query("SELECT
																						products_image
																					FROM
																						".TABLE_PRODUCTS."
																					WHERE
																						products_id = '".$specials->fields['products_id']."'");
														$sInfo_array = array_merge($specials->fields, $products->fields);
														$sInfo = new objectInfo($sInfo_array);
												  	}
	
													if((is_object($sInfo)) && ($specials->fields['specials_id'] == $sInfo->specials_id))
														echo '<tr class="dataTableRowSelected" onmouseover="this.style.cursor=\'poniter\'" onclick="document.location.href=\''.href_link(FILENAME_SPECIALS, 'sID='.$sInfo->specials_id.'&action=edit'.(isset($_GET['page']) ? '&page='.$_GET['page'] : '')).'\'">'."\n";
													else
														echo '<tr class="dataTableRow" onmouseover="this.className=\'dataTableRowOver\';this.style.cursor=\'pointer\'" onmouseout="this.className=\'dataTableRow\'" onclick="document.location.href=\''.href_link(FILENAME_SPECIALS, 'sID='.$specials->fields['specials_id'].(isset($_GET['page']) ? '&page='.$_GET['page'] : '')).'\'">'."\n";
	
												?>
												<td class="dataTableContent"><?php echo $specials->fields['products_name']; ?></td>
												<?php
												reset($groups);
												foreach($groups as $group) {
													echo '	<td class="dataTableContent" align="center">'.
																DiscountByGroup($group['id'], $specials->fields['specials_id']).
															'</td>';
												}
												?>
												<td class="dataTableContent" align="center">
												<?php
													  if ($specials->fields['status'] == '1') {
														echo image(DIR_WS_IMAGES.'icon_status_green.gif', IMAGE_ICON_STATUS_GREEN).' <a href="'.href_link(FILENAME_SPECIALS, 'action=setflag&flag=0&id='.$specials->fields['specials_id'].(isset($_GET['page']) ? '&page='.$_GET['page'] : ''), 'NONSSL').'">'.image(DIR_WS_IMAGES.'icon_status_red_light.gif', IMAGE_ICON_STATUS_RED_LIGHT).'</a>';
													  } else {
														echo '<a href="'.href_link(FILENAME_SPECIALS, 'action=setflag&flag=1&id='.$specials->fields['specials_id'].(isset($_GET['page']) ? '&page='.$_GET['page'] : ''), 'NONSSL').'">'.image(DIR_WS_IMAGES.'icon_status_green_light.gif', IMAGE_ICON_STATUS_GREEN_LIGHT).'</a> '.image(DIR_WS_IMAGES.'icon_status_red.gif', IMAGE_ICON_STATUS_RED);
													  }
												?></td>
																<td class="dataTableContent" align="right"><?php if ( (is_object($sInfo)) && ($specials->fields['specials_id'] == $sInfo->specials_id) ) { echo image(DIR_WS_IMAGES.'icon_arrow_right.gif', ''); } else { echo '<a href="'.href_link(FILENAME_SPECIALS, 'page='.$_GET['page'].'&sID='.$specials->fields['specials_id']).'">'.image(DIR_WS_IMAGES.'icon_info.gif', IMAGE_ICON_INFO).'</a>'; } ?>&nbsp;</td>
												<?php echo '</tr>';
													$specials->MoveNext();
												}
												?>
										</table>
										<table width="100%">
											<tr class="page_break">
												<td class="smallText" valign="top" width="33.3%"><?php echo 'Angezeigt werden '.$query['from'].' bis '.$query['to'].' (von insgesamt '.$query['total'].' Artikeln)'; ?></td>
												<td class="smallText" align="center" width="33.3%"></td>
												<td class="smallText" align="right" width="33.3%">
													Produkte pro Seite: <?php echo $query['page_break']->perSiteDropdown($_GET['page']); ?>
												</td>
											</tr>
											<tr><td align="center" colspan="3"><?php echo '<br />'.$query['links']; ?></td></tr>
										</table>
									</td>
									<?php
									$heading = array();
									$contents = array();
									switch ($_GET['action']) {
										case 'delete':
											$heading[] = array('text' => '<b>'.TEXT_INFO_HEADING_DELETE_SPECIALS.'</b>');
											
											$contents = array('form' => draw_form('specials', FILENAME_SPECIALS, 'sID='.$sInfo->specials_id.'&action=deleteconfirm'.(isset($_GET['page']) ? '&page='.$_GET['page'] : '')));
											$contents[] = array('text' => TEXT_INFO_DELETE_INTRO);
											$contents[] = array('text' => '<br /><b>'.$sInfo->products_name.'</b>');
											$contents[] = array('align' => 'center', 'text' => '<br /><button type="submit" class="button" onclick="this.blur();">'.BUTTON_DELETE.'</button> <a class="button" onclick="this.blur();" href="'.href_link(FILENAME_SPECIALS, 'sID='.$sInfo->specials_id.(isset($_GET['page']) ? '&page='.$_GET['page'] : '')).'">'.BUTTON_CANCEL.'</a>');
										break;
										
										default:
											if (is_object($sInfo)) {
												$heading[] = array('text' => '<b>'.$sInfo->products_name.'</b>');
												$contents[] = array('align' => 'center', 'text' => '<a class="button" onclick="this.blur();" href="'.href_link(FILENAME_SPECIALS, 'sID='.$sInfo->specials_id.'&action=edit'.(isset($_GET['page']) ? '&page='.$_GET['page'] : '')).'">'.BUTTON_EDIT.'</a> <a class="button" onclick="this.blur();" href="'.href_link(FILENAME_SPECIALS, 'sID='.$sInfo->specials_id.'&action=delete'.(isset($_GET['page']) ? '&page='.$_GET['page'] : '')).'">'.BUTTON_DELETE.'</a>');
												$contents[] = array('text' => '<br />'.TEXT_INFO_DATE_ADDED.' '.date_short($sInfo->specials_date_added));
												$contents[] = array('text' => ''.TEXT_INFO_LAST_MODIFIED.' '.date_short($sInfo->specials_last_modified));
												$contents[] = array('align' => 'center', 'text' => '<br />'.product_thumb_image($sInfo->products_image, $sInfo->products_name, SMALL_IMAGE_WIDTH, SMALL_IMAGE_HEIGHT));
												
												$contents[] = array('text' => '<br />'.TEXT_INFO_EXPIRES_DATE.' <b>'.date_short($sInfo->expires_date).'</b>');
												$contents[] = array('text' => ''.TEXT_INFO_STATUS_CHANGE.' '.date_short($sInfo->date_status_change));
											}
										break;
									}
									if ( (not_null($heading)) && (not_null($contents)) ) {
										echo '<td width="25%" valign="top" class="border">'."\n";
											$box = new box;
											echo $box->infoBox($heading, $contents);
										echo '</td>'."\n";
									}
								}
								?>
          						</tr>
        					</table>
        				</td>
      				</tr>
    			</table>
    		</td>
  		</tr>
	</table>
</div>
<?php require(DIR_WS_INCLUDES.'footer.php'); ?>
</body>
</html>
<?php require(DIR_WS_INCLUDES.'application_bottom.php');